package com.china08.yxyapi.schedule.webgroup;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.entity.db.sws.SwsGroup;
import com.china08.yxyapi.entity.db.sws.SwsSetting;
import com.china08.yxyapi.entity.db.sws.SwsSettingDomains;
import com.china08.yxyapi.entity.mg.sws.SwsArticle;
import com.china08.yxyapi.entity.mg.sws.SwsPvForTotalAnalyze;
import com.china08.yxyapi.repository.db.SwsGroupRepository;
import com.china08.yxyapi.repository.db.SwsSettingDomainsRepository;
import com.china08.yxyapi.repository.db.SwsSettingRepository;
import com.china08.yxyapi.repository.mg.SwsArticleRepository;
import com.china08.yxyapi.repository.mg.SwsPvForTotalAnalizeRepository;
import com.china08.yxyapi.util.YxyScheduleRunnableUtil;

@Component
@EnableScheduling
public class WebGroupSchedule {

    static final Logger LOGGER = LoggerFactory.getLogger(WebGroupSchedule.class);

    @Autowired
    SwsSettingRepository swsSettingRepository;

    @Autowired
    SwsSettingDomainsRepository domainsRepository;

    @Autowired
    SwsGroupRepository swsGroupRepository;

    @Value(value = "${yx.rest.api.yx.path}")
    private String yxyApiYxUrl;

    @Autowired
    SwsArticleRepository swsArticleRepository;

    @Autowired
    SwsPvForTotalAnalizeRepository swsPvForTotalAnalizeRepository;

    @Autowired
    RestTemplate restTemplate;

    // @Scheduled(fixedRate = 1000 * 60 * 2)
    @Scheduled(cron = "0 15 3 * * ?")
    public void execute() throws UnknownHostException {

        // ##
        // 检测定时任务是否可执行
        if (!YxyScheduleRunnableUtil.checkRunnable()) { return; }

        System.out.println("开始同步数据");

        // 获取所有有网站域名的学校
        List<SwsSettingDomains> domainsList = domainsRepository.findByDomainNameIsNotNull();

        // 去掉重复的数据:旧平台一个学校可以设置多个域名
        Set<String> set = new HashSet<>();
        // 测试学校集合
        List<String> testSchool = new ArrayList<String>();
        testSchool.add("4028e52d5b040fbb015b0440cc670006");
        testSchool.add("ff80808148f98a490148fcdab1760008");
        testSchool.add("ff8080815ccd85bd015d828eb2b5741f");
        testSchool.add("ff808081598c885c01599b2857f52de7");
        testSchool.add("ff8080815a032de4015a3c0fdf2d7a16");
        testSchool.add("ff8080815ac67d12015b03a25cf70a5c");

        for (SwsSettingDomains domains : domainsList) {
            String schoolId = domains.getSchoolId();
            String webUrl = domains.getDomainName();
            System.out.println("站群[" + schoolId + "||" + webUrl);

            // 学校为空，不统计
            if (StringUtils.isBlank(schoolId) || "null".equals(schoolId)) {
                continue;
            }

            // 域名为空，不统计
            if (StringUtils.isBlank(webUrl) || "null".equals(webUrl)) {
                continue;
            }

            // 如果是测试学校，不统计
            if (testSchool.contains(schoolId)) {
                continue;
            }

            // 1版本云校网站域名规则
            boolean is91yunxiao = StringUtils.contains(webUrl, "sch.91yunxiao.com");
            // 2版本云校网站域名规则
            boolean is91eduy = StringUtils.contains(webUrl, "91eduy.com");
            // 1版本哈尔滨网站域名规则
            boolean ishrbeduy1 = StringUtils.contains(webUrl, "sch.hrbeduy.com");
            // 2版本哈尔滨网站域名规则
            boolean ishrbeduy2 = StringUtils.contains(webUrl, "hrbeduy.com");
            // 1版兰州网站域名规则
            boolean islanzhou = StringUtils.contains(webUrl, "lanzhou.edu.cn");
            System.out.println("==================");
            System.out.println("1版本云校网站域名规则" + is91yunxiao);
            System.out.println("2版本云校网站域名规则" + is91eduy);
            System.out.println("1版本哈尔滨网站域名规则" + ishrbeduy1);
            System.out.println("2版本哈尔滨网站域名规则" + ishrbeduy2);
            System.out.println("1版兰州网站域名规则" + islanzhou);

            // 非新平台域名，不统计
            if (!is91yunxiao && !ishrbeduy1 && !ishrbeduy2 && !islanzhou && !is91eduy) {
                continue;
            }
            set.add(schoolId);
        }
        System.out.println("==================");
        System.out.println(set);
        System.out.println("==================");
        for (String schoolId : set) {
            System.out.println("站群定时更新学校id:[" + schoolId + "]");
            // 获取学校基本数据
            Map<String, Object> map = restTemplate.getForObject(yxyApiYxUrl + "/comm/school/all/" + schoolId,
                    Map.class);
            if (map == null) {
                System.out.println("未获取学校：[" + schoolId + "]");
                continue;
            }
            String schoolName = map.get("schoolNick") + "";
            System.out.println("站群定时更新学校schoolNick[" + schoolName + "]");
            String areaIdProvince = map.get("areaIdProvince") + "";
            String areaIdCity = map.get("areaIdCity") + "";
            String areaIdDistrict = map.get("areaIdDistrict") + "";
            String areaNameProvince = map.get("areaNameProvince") + "";
            String areaNameCity = map.get("areaNameCity") + "";
            String areaNameDistrict = map.get("areaNameDistrict") + "";
            String address = map.get("address") + "";
            List<String> schoolTypes = (List<String>) map.get("schoolTypeList");

            Boolean isSt0 = false;
            Boolean isSt1 = false;
            Boolean isSt2 = false;
            Boolean isSt3 = false;
            if (schoolTypes != null) {
                if (schoolTypes.contains("ST0")) {
                    isSt0 = true;
                }
                if (schoolTypes.contains("ST1")) {
                    isSt1 = true;
                }
                if (schoolTypes.contains("ST2")) {
                    isSt2 = true;
                }
                if (schoolTypes.contains("ST3")) {
                    isSt3 = true;
                }
            }

            // 网站总访问量
            Long pv = 0L;
            SwsPvForTotalAnalyze swsPvForTotalAnalyze = swsPvForTotalAnalizeRepository
                    .findTop1BySchoolIdOrderByPvDesc(schoolId);
            if (swsPvForTotalAnalyze != null) {
                pv = swsPvForTotalAnalyze.getPv();
            }

            // 学校设置校徽
            String schoolBadge = "";
            SwsSetting swsSetting = swsSettingRepository.findBySchoolId(schoolId);
            if (swsSetting != null) {
                schoolBadge = swsSetting.getSchoolBadge();
            }
            // 最新资讯时间,最后修改时间
            Date LatestArticleDate = null;
            SwsArticle swsArticle = swsArticleRepository
                    .findTop1ByOwnerSchoolIdAndAuditStatusOrderByUpdateDateDesc(schoolId, 1);
            if (swsArticle != null) {
                LatestArticleDate = swsArticle.getUpdateDate();
            }
            // 没有资讯，设置网站开通时间
            else {
                if (swsSetting != null) {
                    LatestArticleDate = swsSetting.getCreatedDate();
                }
            }

            // 资讯总数量
            Long articleCount = swsArticleRepository.countByOwnerSchoolIdAndAuditStatusAndIdNotNull(schoolId, 1);

            String webUrl = "";
            for (SwsSettingDomains domains : domainsList) {
                if (domains.getSchoolId().equals(schoolId) && StringUtils.isNotBlank(domains.getDomainName())
                        && !"null".equals(domains.getDomainName())) {
                    webUrl = domains.getDomainName();
                    break;
                }
            }

            // 获取站群
            SwsGroup swsGroup = swsGroupRepository.findBySchoolId(schoolId);
            if (null == swsGroup) {
                swsGroup = new SwsGroup();
                swsGroup.setSchoolId(schoolId);
                swsGroup.setRecommendCity(false);
                swsGroup.setRecommendDistrict(false);
                swsGroup.setRecommendProvince(false);
                swsGroup.setTest(false);
            }
            swsGroup.setSchoolName(schoolName);
            swsGroup.setAddress(address);
            swsGroup.setAreaIdProvince(areaIdProvince);
            swsGroup.setAreaIdCity(areaIdCity);
            swsGroup.setAreaIdDistrict(areaIdDistrict);
            swsGroup.setAreaNameProvince(areaNameProvince);
            swsGroup.setAreaNameCity(areaNameCity);
            swsGroup.setAreaNameDistrict(areaNameDistrict);
            swsGroup.setIsSt0(isSt0);
            swsGroup.setIsSt1(isSt1);
            swsGroup.setIsSt2(isSt2);
            swsGroup.setIsSt3(isSt3);
            swsGroup.setWebUrl(webUrl);
            swsGroup.setPv(pv);
            swsGroup.setSchoolBadge(schoolBadge);
            swsGroup.setArticleCount(articleCount);
            swsGroup.setLatestArticle(LatestArticleDate);
            swsGroupRepository.save(swsGroup);
        }
        LOGGER.info("=======定时更新数据成功=======");
    }
}
